﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Customer_Profile.eCard.DBDao;
using KVB.Common;
using System.IO;
using Customer_Profile.Admin;

namespace Customer_Profile.eCard.Match
{
    public partial class match : System.Web.UI.Page
    {
        string strUserID = "";
        string strUserName = "";
        string deal_no = "";
        string type = "";
        public string strScript = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }

            if (Request["deal_no"] != null)
                deal_no = Request["deal_no"].ToString();
            if (Request["type"] != null)
                type = Request["type"].ToString();

            if (!Page.IsPostBack)
            {
                Comm.BindDll(ref dropBank, "netbank_name", false, "");
                bindDetailInfo(int.Parse(deal_no));
                txtcreatedatebegin.Text = DateTime.Now.ToString("yyyy-MM-dd");
                bindTransferGrid(int.Parse(deal_no));
                calcValueDueDate(int.Parse(deal_no));
                bindNetGrid(txtcreatedatebegin.Text);
            }
        }
        //计算起息日和到期日
        private void calcValueDueDate(int deal_no)
        {
            //1，普通的以审核当天为起息日，到期日根据客户购买的产品加上月份
            //2, 如果客户买的特殊系列产品，也就是产品的起息日和到期日是指定的，则读取产品产品的起息日和到期日。
            //3, 如果是个人旅行卡，或者大集卡转存过来的，则需要人工指定起息日和到期日。
            //4, 如果是续存，分为2种情况，如果是在到期前提交续存申请，则起息日为上一笔的到期日+1天。
            //                            如果是到期后提交的续存申请，则起息日为批准日期，也就是当前操作日期。
            try
            {
                DataSet ds = netBankDao.CalcValueDate(deal_no);
                txtValue_date.Text = ds.Tables[0].Rows[0]["value_date"].ToString();
                txtDue_date.Text = ds.Tables[0].Rows[0]["due_date"].ToString();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        private void bindDetailInfo(int deal_no)
        {
            try
            {
                DataSet ds = netBankDao.getDealAllInfo(deal_no);
                //客户信息
                rptCparty.DataSource = ds.Tables[0].DefaultView;
                rptCparty.DataBind();
                //交易信息
                rptDeals.DataSource = ds.Tables[1].DefaultView;
                rptDeals.DataBind();
                //附件
                rptAttach.DataSource = ds.Tables[2].DefaultView;
                rptAttach.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        private void bindNetGrid(string strDate)
        {
            try
            {
                string strBankName = dropBank.SelectedItem.Text.Trim();
                DataSet ds = netBankDao.getNetbankDetailbyDate(strDate,strBankName);
                if (ds != null && ds.Tables.Count > 0)
                {
                    gridNetbank.DataSource = ds.Tables[0];
                    gridNetbank.DataBind();
                }
                else
                {
                    gridNetbank.DataBind();
                }
                gridNetbank.Selection.UnselectAll();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindNetGrid", ex.ToString());
            }
        }

        private void bindTransferGrid(int deal_no)
        {
            try
            {
                DataSet ds = netBankDao.getMatchTransfer(deal_no);
                if (ds != null && ds.Tables.Count > 0)
                {
                    gridTransfer.DataSource = ds.Tables[0];
                    gridTransfer.DataBind();
                }
                else
                {
                    gridTransfer.DataBind();
                }
                gridTransfer.Selection.UnselectAll();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindTransferGrid", ex.ToString());
                Response.Write(ex.ToString());
            }
        }

        protected void gridNetbank_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            try
            {
                string cparty_accountinfo = e.Parameters.ToString();
                gridNetbank.Selection.UnselectAll();

                if (cparty_accountinfo != "" && gridTransfer.Selection.Count.ToString() == "1")
                {
                    string[] account_infos = cparty_accountinfo.Split(',');
                    //Log.WriteDefaultLog("相关信息：", cparty_accountinfo);
                    for (int i = 0; i < gridNetbank.VisibleRowCount; i++)
                    {
                        if (gridNetbank.GetRowValues(i, "cparty_accountname") != null && gridNetbank.GetRowValues(i, "cparty_accountno") != null && gridNetbank.GetRowValues(i, "crebit_amount") != null)
                        {
                            if (gridNetbank.GetRowValues(i, "cparty_accountname").ToString().Trim() == account_infos[0].Trim() && gridNetbank.GetRowValues(i, "cparty_accountno").ToString().Trim() == account_infos[1].Trim() && gridNetbank.GetRowValues(i, "crebit_amount").ToString().Trim() == account_infos[2].Trim())
                                gridNetbank.Selection.SelectRow(i);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnMatch_Click(object sender, EventArgs e)
        {
            try
            {
                //更新汇款状态，并标记对应的银行信息是那一笔？ 检查mmdeals的所有汇款是否已经全部审核完毕，如果全部审核完毕则更新状态为审核完毕，
                //并更新起息日与到期日。
                //更新银行信息表，剩余余额。            
                string transfer_id = hidTransferid.Value.ToString().Trim().Substring(0, hidTransferid.Value.ToString().Trim().Length - 1);
                string accounting_key = hidAccountingKey.Value.ToString().Trim().Substring(0, hidAccountingKey.Value.ToString().Trim().Length - 1);

                if (transfer_id.Split(',').Length > 1)
                {
                    lbWarning.Text = "每次只能匹配一条付款信息";
                }

                if (accounting_key.Split(',').Length > 1)
                {
                    lbWarning.Text = "每次只能匹配一条银行流水信息";
                }

                string status = "";
                string message = "";
                bool bok = netBankDao.MatchAction(strUserID, transfer_id, accounting_key, out status, out message);
                if (bok)
                {
                    bindNetGrid(txtcreatedatebegin.Text);
                    bindTransferGrid(int.Parse(deal_no));
                    hidTransferid.Value = "";
                    hidAccountingKey.Value = "";
                    lbWarning.Text = "资金匹配成功！";
                    strScript = "<script>alert('资金匹配成功！');</script>";
                }
                else
                {
                    lbWarning.Text = message;
                    strScript = "<script>alert('" + message + "');</script>";
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void txtSearch_Click(object sender, EventArgs e)
        {
            try
            {
                bindNetGrid(txtcreatedatebegin.Text);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnPass_Click(object sender, EventArgs e)
        {
            try
            {
                //1, 验证，汇款是否都已经对应上了，
                //2, 验证是否没有被其他人通过了或者退回。
                //3, 修改cflow账户里面，
                //4, 更新卡内余额，
                //5, 修改订单状态为通过审核状态,修改起息日，到期日，通过备注。
                //6, 关闭页面，刷新父页面。
                string review_status = "";
                string message = "";
                string value_date = txtValue_date.Text.Trim();
                string due_date = txtDue_date.Text.Trim();
                string pass_remark = txtPassRemark.Text.Trim();
                netBankDao.Review(int.Parse(deal_no), strUserID, value_date, due_date, pass_remark, out review_status, out message);

                if (review_status == "Y")
                {
                    strScript = "<script>alert('审核成功！'); window.opener.refresh();window.opener=null;window.close();</script>";
                }
                else
                {
                    lbWarning.Text = review_status + "\r\n" + message;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                //1, 验证是否没有被其他人通过了或者退回。
                //2, 修改订单状态为退回状态。
                //3, 如果汇款账户已经匹配，要解锁匹配，更新银行对账单里面的余额。
                //4, 关闭页面，刷新父页面。

                string review_status = "";
                string message = "";
                string back_reason = txtBackReason.Text.Trim();
                netBankDao.Review_Back(int.Parse(deal_no), strUserID, back_reason, out review_status, out message);

                if (review_status == "Y")
                {
                    strScript = "<script>alert('退回成功！'); window.opener.refresh();window.opener=null;window.close();</script>";
                }
                else
                {
                    lbWarning.Text = review_status + "\r\n" + message;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnUnMatch_Click(object sender, EventArgs e)
        {
            try
            {
                //更新汇款状态，并标记对应的银行信息是那一笔？ 检查mmdeals的所有汇款是否已经全部审核完毕，如果全部审核完毕则更新状态为审核完毕，
                //并更新起息日与到期日。
                //更新银行信息表，剩余余额。            
                string transfer_id = hidTransferid.Value.ToString().Trim().Substring(0, hidTransferid.Value.ToString().Trim().Length - 1);
                string accounting_key = hidAccountingKey.Value.ToString().Trim().Substring(0, hidAccountingKey.Value.ToString().Trim().Length - 1);

                if (transfer_id.Split(',').Length > 1)
                {
                    lbWarning.Text = "每次只能解锁一条付款信息";
                    strScript = "<script>alert('每次只能解锁一条付款信息！');</script>";
                }

                if (accounting_key.Split(',').Length > 1)
                {
                    lbWarning.Text = "每次只能解锁一条银行流水信息";
                    strScript = "<script>alert('每次只能解锁一条银行流水信息！');</script>";
                }

                string status = "";
                string message = "";
                bool bok = netBankDao.UnMatchAction(strUserID, transfer_id, accounting_key, out status, out message);
                if (bok)
                {
                    bindNetGrid(txtcreatedatebegin.Text);
                    bindTransferGrid(int.Parse(deal_no));
                    hidTransferid.Value = "";
                    hidAccountingKey.Value = "";
                    lbWarning.Text = "资金匹配解锁成功！";
                    strScript = "<script>alert('资金匹配解锁成功！');</script>";
                }
                else
                {
                    lbWarning.Text = message;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }               
    }
}